package com.seven.back.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.seven.back.gateway.config.WhiteConfig;
import com.seven.utils.JWTUtil;
import com.seven.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Author： longlong
 * @Date： 2024/3/1 9:34
 * @Describe：
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {

    @Autowired
    private WhiteConfig whiteConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1 获取request对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2 获取访问的资源路径
        String path = request.getPath().toString();
        //3 是否属于白名单 【无须认证即可访问的资源】是就直接放行了是这个意思
        List<String> list = whiteConfig.getList();
        if (list.contains(path)){
           return chain.filter(exchange);
        }
        //4获取到token --请求头
        String token = request.getHeaders().getFirst("token");
        //现在我们校验token使用手动校验
        // 未来我们使用JWT（之前学过的生成token的组件）来验证token是否有效 && JWTUtil.verifyToken(token)
        // todo 加入redis判断
        if(token !=null && JWTUtil.verifyToken(token)){
            return chain.filter(exchange);
        }
        //如果都不通过则返回一个json数据
        Result result = new Result(4002, "登录无效",null);
        //做json格式转换--没有则引入fastjson依赖
        byte[] bytes = JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        //调用bufferFactory方法生成DataBuffer对象
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        // 调用Mono中just方法返回要写给前端的json数据
        return response.writeWith(Mono.just(buffer));

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
